//  Copyright (c) 2008  Yoong-ki Ahn & Youngjin Kim < mexif@googlegroups.com>
//  See the enclosed file COPYING for license information (MIT Licence).
//  If you did not receive this file,
//  see http://www.opensource.org/licenses/mit-license.php.

#include "stdafx.h"
#include "Picture.h"

CPicture::CPicture() 
{
	picture_ = 0;
}

CPicture::~CPicture() 
{
	Close();
}

BOOL CPicture::LoadFromBuffer( const BYTE* buff, UINT nSize ) 
{
	bool ret = false;

	HGLOBAL hGlobal = GlobalAlloc( GMEM_MOVEABLE, nSize );
	{
		void* p = GlobalLock( hGlobal );
		memcpy( p, buff, nSize );
		GlobalUnlock( hGlobal );
	}

	IStream* stream = 0;
	if ( CreateStreamOnHGlobal( hGlobal, TRUE, &stream ) == S_OK )
	{
		HRESULT hr;
		if ( (hr = OleLoadPicture( stream, nSize, FALSE, IID_IPicture, (LPVOID*) &picture_ ) ) == S_OK )
			ret = true;

		ASSERT( SUCCEEDED(hr) );
		stream->Release();
	}

	return ret;
}

BOOL CPicture::Draw(CDC* pDC, int x, int y, int cx, int cy)
{
	long hmWidth;
	long hmHeight;
	picture_->get_Width(&hmWidth);
	picture_->get_Height(&hmHeight);

	if (picture_->Render(pDC->m_hDC, x, y, cx, cy, 0, hmHeight, hmWidth, -hmHeight, NULL) == S_OK)
		return true;

	return false;
}

void CPicture::Close() 
{
	if ( picture_ )
	{
		picture_->Release();
		picture_ = 0;
	}
}

CSize CPicture::GetSize( CDC* pDC ) 
{
	CSize rcResult = CSize(0,0);

	if (picture_ != NULL)
	{
		long hmWidth;
		long hmHeight;
		picture_->get_Width(&hmWidth);
		picture_->get_Height(&hmHeight);

		rcResult.cx     = MulDiv(hmWidth,       pDC->GetDeviceCaps(LOGPIXELSX), HIMETRIC_INCH);
		rcResult.cy     = MulDiv(hmHeight,      pDC->GetDeviceCaps(LOGPIXELSY), HIMETRIC_INCH);
	}

	return rcResult;
}


